package com.dc.datacollect.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie工具
 * @author zhuangjie
 * @date 2023/06/29
 */
public class CookieUtils {
    /**
     * 添加饼干
     *
     * @param key    key
     * @param value  value
     * @param maxAge 最大年龄，单位为秒 (当前时间+maxAge=过期时间)
     * @param path   路径
     */
    public static void addCookie(String key, String value, Integer maxAge, String path){
        HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(maxAge);
        if (path != null) {
            cookie.setPath(path);
        }
        response.addCookie(cookie);
    }
    public static void addCookie(String key, String value, Integer maxAge){
        addCookie(key,value,maxAge,null);
    }
    public static void addCookie(HttpServletResponse response, String key, String value, Integer maxAge){
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(maxAge);

        response.addCookie(cookie);
    }
    public static String getCookie(String key){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request == null) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null) return null;
        System.out.println(cookies);
        for (Cookie cookie:cookies){
            if(key.equals(cookie.getName())){
                return cookie.getValue();

            }
        }
        return null;
    }

    /**
     * 删除饼干
     *
     * @param key   饼干的键
     * @param path  路径
     */
    public static void removeCookie(String key, String path) {
        addCookie(key,null,0,path);
    }
    public static void removeCookie(String key) {
        removeCookie(key,null);
    }

}
